package org.boot.easyapi.util.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 通用导出Excel工具
 */
@Slf4j
@SuppressWarnings("all")
public class ExcelExporterUtil {

    /**
     * 导出Excel，响应byte[]字节码数据
     * @param list
     * @return
     */
    public static byte[] exportExcel(List<Map<String, Object>> list) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("data");

        // 创建表头
        if (!list.isEmpty()) {
            Map<String, Object> firstRow = list.get(0);
            Row headerRow = sheet.createRow(0);
            int columnIndex = 0;
            for (String key : firstRow.keySet()) {
                Cell cell = headerRow.createCell(columnIndex++);
                cell.setCellValue(key);
            }

            // 填充数据
            int rowIndex = 1;
            for (Map<String, Object> rowData : list) {
                Row dataRow = sheet.createRow(rowIndex++);
                columnIndex = 0;
                for (Object value : rowData.values()) {
                    Cell cell = dataRow.createCell(columnIndex++);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }
        }

        // 调整列宽
        for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入字节数组输出流以获取字节码
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            workbook.write(byteArrayOutputStream);
        } catch (IOException e) {
            log.error("将工作簿写入字节数组输出流时发生异常：", e);
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error("关闭工作簿时发生异常：", e);
                e.printStackTrace();
            }
        }
        // 获取字节码数组
        return byteArrayOutputStream.toByteArray();
    }









}
